/**
 * 	@author: An Bui
 * 	@email: btan@tma.com.vn - anbtan@gmail.com
 */
package com.vital.mshopping;

import java.net.URLEncoder;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONObject;

import com.vital.service.DatabaseService;
import com.vital.service.HttpService;

import com.vital.dao.Category;
import com.vital.dao.Location;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

public class LocationActivity extends Activity {
	ListView lvLocation;
	ArrayList<Location> locations;
	LocationAdapter adapterLocation;
	Category category;
	Context mContext;
	double lat;
	double lng;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_venue);
		
		mContext = this.getApplicationContext();
		lvLocation = (ListView)findViewById(R.id.lvVenue);
		locations = new ArrayList<Location>();
		
		Bundle b = getIntent().getExtras();
		if (b != null) {
			category = (Category)b.getSerializable("category");
			lat = (Double)b.getDouble("latitute");
			lng = (Double)b.getDouble("longtitute");
			String categoryName = category.getCateName();

			String urlEncoder = URLEncoder.encode(categoryName);
			//Toast.makeText(getApplicationContext(), "Lat: "+lat+"-Longtitute:"+lng, Toast.LENGTH_LONG).show();
			String url = "http://ajax.googleapis.com/ajax/services/search/local?q="+urlEncoder+
					"&rsz=8&sll="+lat+","+lng+"&v=1.0&start=0";
				
			new LoadListLocationsTask().execute(url);
			
		}
	}

	private void setApdaterLocation() {
		adapterLocation = new LocationAdapter(getApplicationContext(), R.layout.item_location, locations);
		lvLocation.setOnItemClickListener(onItemClickListener);
		lvLocation.setAdapter(adapterLocation);
	};
	
	private OnItemClickListener onItemClickListener = new OnItemClickListener() {

		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			// TODO Auto-generated method stub
			Location location = new Location();
			location = locations.get(position);
			
			//---Start Detail location---
			Bundle b = new Bundle();
			Intent intent = new Intent(getApplicationContext(), DetailLocationActivity.class);
			b.putSerializable("location_detail", location);
			intent.putExtras(b);
			startActivity(intent);
			
		}
	};
	
	/**
	 * Load List Location base on Category name
	 */
	private class LoadListLocationsTask extends AsyncTask<String, Void, String> {
		
		private final ProgressDialog progress = new ProgressDialog(LocationActivity.this);
		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			progress.setMessage("Loading...");
			progress.show();
		}
		
		@Override
		protected String doInBackground(String... params) {
			// TODO Auto-generated method stub
			HttpService httpService = new HttpService();
			return httpService.getStringJson(params[0]);
		}
		
		@Override
		protected void onPostExecute(String jsString) {
			try {
				JSONObject jsObject = new JSONObject(jsString);
				JSONObject responseData = jsObject.getJSONObject("responseData");
				JSONArray results = responseData.getJSONArray("results");
				
				int length = results.length();
				for (int i = 0; i < length; i++) {
					JSONObject result = results.getJSONObject(i);
					//---Latitute and Longtitute---
					float lat = Float.parseFloat(result.getString("lat"));
					float lng = Float.parseFloat(result.getString("lng"));
					//---Accuracy---
					String accuracy = result.getString("accuracy");
					//---Title name---
					String name = result.getString("titleNoFormatting");
					//---Phone number---
					String phone  = "";
					try {
						JSONArray phones = result.getJSONArray("phoneNumbers");
						JSONObject objPhone = phones.getJSONObject(0);
						phone += objPhone.getString("number");
					} catch (Exception e) {
						// TODO: handle exception
						phone = "N/A";
						e.printStackTrace();
					}
					//---Address---
					String address = "";
					JSONArray addresses = result.getJSONArray("addressLines");
					for (int j = 0; j < addresses.length(); j++) {
						address += addresses.getString(j) + ", ";
					}
					//---Category id---
					int categoryId = category.getCateId();
					//---Create obj Location---
					//Location location = new Location();
					Location location = new Location(lat, lng, accuracy, name, phone, address, categoryId);
					
					//---Insert this location to DB---
					//---Insert to LOCATION TABLE---
					DatabaseService db = new DatabaseService(mContext);
					db.open();
					long locationId = db.insertLocation(location);
					if (locationId > -1) {
						location.setId((int)locationId);
						locations.add(location);
						
					}
					db.close();
					
				}
				//---Set adapter locations---
				setApdaterLocation();
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}
			
			if (progress.isShowing()) {
				progress.dismiss();
			}
		}

		
	}
	
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_location, menu);
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		switch (item.getItemId()) {
			case R.id.location_menu_mapview:
				Intent intent = new Intent(getApplicationContext(), MapViewActivity.class);
				intent.putExtra("mapview_serializable", locations);
				startActivity(intent);
				break;
		}
		return super.onOptionsItemSelected(item);
		
	}
}
